package com.kiell.gulimall.order.listener;

import com.kiell.common.to.mq.SeckillOrderTo;
import com.kiell.gulimall.order.entity.OrderEntity;
import com.kiell.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @projectName: guli-mall
 * @package: com.kiell.gulimall.order.listener
 * @className: OrderSeckillListener
 * @author: HuangZeWei
 * @description: 监听秒杀创建订单的队列
 * @date: 2024/5/8 10:05
 */
@Slf4j
@RabbitListener(queues = "order.seckill.order.queue")
@Component
public class OrderSeckillListener {
    @Autowired
    OrderService orderService;

    @RabbitHandler
    public void listener(SeckillOrderTo entity, Channel channel, Message message) throws IOException {
        log.info("收到秒杀创建订单信息：准备创建订单！sn:{}",entity.getOrderSn());
        try {
            orderService.createSeckillOrder(entity);
            //肯定，让broker将移除此消息，以后不用重试。
            //参数deliveryTag号是消息的唯一标识，参数false代表不批量确认此deliveryTag编号之前的所有消息
            //TODO 订单到时自动取消，但支付宝收单时间未到(可能)。则需要手动调用支付宝收单接口
            //coding
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //拒绝；参数deliveryTag号是消息的唯一标识；参数true代表重新回队列，如果false则代表丢弃
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }

    }
}
